from django.http import JsonResponse
from django.shortcuts import redirect
from django.views.decorators.cache import cache_page
from django_redis import get_redis_connection
from redis import RedisError

from polls.mappers import SubjectMapper, SubjectSimpleMapper, TeacherMapper
from polls.models import Subject, Teacher


def index(request):
    """首页"""
    return redirect('/static/html/subjects.html')


@cache_page(timeout=3600, cache='default')
def show_subjects(request):
    """获取所有学科"""
    queryset = Subject.objects.all()
    subjects = [SubjectMapper(subject).as_dict()
                for subject in queryset]
    return JsonResponse(subjects, safe=False)


def show_teachers(request):
    """获取指定学科的老师"""
    try:
        sno = request.GET['sno']
        subject = Subject.objects.get(no=sno)
        queryset = Teacher.objects\
            .filter(subject__no=sno).defer('subject')
        teachers = [TeacherMapper(teacher).as_dict()
                    for teacher in queryset]
        data = {
            'code': 20000,
            'subject': SubjectSimpleMapper(subject).as_dict(),
            'teachers': teachers
        }
    except (KeyError, ValueError, Subject.DoesNotExist):
        data = {'code': 20001, 'message': '请求老师数据失败'}
    return JsonResponse(data)


def praise_or_criticize(request):
    """好评或差评"""
    tno = request.GET.get('tno', '0')
    try:
        redis_cli = get_redis_connection()
        key = f'django19062:polls:{tno}'
        if not redis_cli.exists(key):
            redis_cli.hmset(key, {'good': 0, 'bad': 0})
        if request.path.startswith('/praise'):
            redis_cli.hincrby(key, 'good', 1)
        else:
            redis_cli.hincrby(key, 'bad', 1)
        data = {'code': 10000, 'message': '操作成功'}
    except RedisError:
        data = {'code': 10001, 'message': '操作失败'}
    return JsonResponse(data)

# 通过定时任务和异步任务每隔一段时间就将Redis中投票的数据
# 合并到数据库的表中，这样的话最终投票的数据是正确的
# 要实现定时任务可以使用APScheduler或Celery三方库
